package com.leyou.auth.service.impl;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.constants.RedisConstants;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDto;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;


@Service
public class UserAuthServiceImpl implements UserAuthService {

    @Autowired
    UserClient userClient;

    @Autowired
    JwtUtils jwtUtils;


    @Override
    public void login(String username, String password, HttpServletResponse response) {
        try {
            UserDto userDto = userClient.queryUserByUsernameAndPassword(username, password);
            if (userDto == null) {
                throw new LyException(403, "账号密码错误");
            }

            UserDetail userDetail = UserDetail.of(userDto.getId(), userDto.getUsername());
            String token = jwtUtils.createJwt(userDetail);

            writeCookie(response, token);
        } catch (FeignException e) {
            // 把远程调用异常转换抛出
            throw new LyException(e.status(), e.contentUTF8());
        }
    }

    private void writeCookie(HttpServletResponse response, String token) {
        Cookie cookie = new Cookie(JwtConstants.COOKIE_NAME, token);
        cookie.setDomain(JwtConstants.DOMAIN);
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        cookie.setMaxAge(-1);
        response.addCookie(cookie);
    }
}